package com.chidopi.market.aa.actions;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.exception.CdfException;
import com.chidopi.cdf.service.IBaseService;
import com.chidopi.cdf.struts1actions.StandardOperatorAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.aa.domain.Accounts;
import com.chidopi.market.util.MessageHandler;


public class AccountAction extends StandardOperatorAction<Accounts> {
	private static Logger logger = LoggerFactory.getLogger(AccountAction.class);
	private IBaseService<Accounts> baseService;

	public AccountAction(){
		this("");
	}
	
	@SuppressWarnings("unchecked")
	public AccountAction(String entryURL) {
		this.entryURL = entryURL;
		try {
			this.baseService = (IBaseService<Accounts>)
				ModelContextFactory.get("accountService", IBaseService.class);
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
	}

	public ActionForward back(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("success");
	}

	private static final String[] conditions =
		{"username", "name_tw", "name_en", "email", "enable_flag"};
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (null == this.baseService) return mapping.findForward("error");
		StringBuffer sql = new StringBuffer();
		for (String cond : conditions) {
			String value = (String) request.getParameter(cond);
			if (value == null || value.trim().equals("")) continue;
			logger.debug(cond + "=" + value);
			if (cond.equals("enable_flag")) {
				String disable_flag = (String) request.getParameter("disable_flag");
				if (disable_flag != null) continue;
			}
			if (sql.length() > 1) sql.append("and ");
			if (cond.endsWith("_flag")) {
				sql.append("enable_flag = '" + value + "' ");
			} else {
				sql.append(cond + " like '%" + value + "%' ");
			}
		}
		logger.debug("sql=" + sql.toString());
		List<Accounts> list = this.baseService.find(sql.toString());
		logger.debug("size=" + list.size());
		JSONArray json = JSONArray.fromObject(list);

		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Accounts t = this.baseService.findById(new Integer(id));
		if (null == t) {
			logger.warn("Account[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "delete");
		dynaForm.set("vo", t);
		return mapping.findForward("success");
	}

	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Accounts t = this.baseService.findById(id);
		if (null == t) t = new Accounts();
		//t.setId(this.baseService.getNextSequence());
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "insert");
		dynaForm.set("vo", t);
		return mapping.findForward("success");
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Accounts t = this.baseService.findById(id);
		if (null == t) {
			logger.warn("Account[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "update");
		dynaForm.set("vo", t);
		return mapping.findForward("success");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String op = request.getParameter("op");
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		logger.debug("op=" + op);
		Accounts t = new Accounts();
		try {
			DynaBean dynaForm = (DynaBean) form;
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			logger.debug(t.getId() + ":" + t.getName_tw() + "/" + t.getEmail());
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}

		int ret = -1;
		if ("insert".equals(op)) {
			t.setCreate_by(userId);
			t.setPassword(Accounts.ACCOUNT_PASSWORD_DEFAULT);
			ret = this.baseService.insert(t);
		} else if ("update".equals(op)) {
			t.setUpdate_by(userId);
			ret = this.baseService.update(t);
		} else if ("delete".equals(op)) {
			t.setUpdate_by(userId);
			try{
				ret = this.baseService.delete(t);
			}catch(CdfException cex){
				MessageHandler.getInstance().processError(request, cex.getMessage());
			}			
		}
		if (ret > -1) {
			request.setAttribute("entryURL", entryURL);
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}
	
	public ActionForward ajaxValidateAccount(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String username = request.getParameter("username");
		
		logger.debug("username= " + username);
		String sql = "username = ?";
		List<Accounts> list = this.baseService.find(sql, username);
		if (null == list || list.isEmpty()) {
			MessageHandler.getInstance().processAjaxMessage(response,"OK");
		}else{			
			String message = MessageHandler.getInstance().getResourceMessage(request,"error.accout.username.duplicate");
			logger.warn(message);
			MessageHandler.getInstance().processAjaxMessage(response,message);
			
		}
		return null;
	}


	@Override
	public Accounts newValueObject() {
		return new Accounts();
	}
}
